import axios from 'axios';

//const API_BASE_URL = 'http://101.42.2.4:8004/api';
const API_BASE_URL = 'http://117.72.106.234:8080/api';

// 创建axios实例
const userApi = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加token
userApi.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;  
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理token过期
userApi.interceptors.response.use(
  (response) => response,
  async (error) => {
    if (error.response?.status === 401) {
      // token过期，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export const userService = {
  // 用户管理API
  changePassword: (data) => {
    return userApi.put(`${API_BASE_URL}/user/change-password`, data);
  },

  generatePasskey: () => {
    return userApi.post(`${API_BASE_URL}/user/passkey`);
  },

  getCurrentPasskey: () => {
    return userApi.get(`${API_BASE_URL}/user/passkey`);
  },

  getPasskeyHistory: (params) => {
    return userApi.get(`${API_BASE_URL}/user/passkey/history`, { params });
  },

  verifyPasskey: (data) => {
    return userApi.post(`${API_BASE_URL}/user/verify-passkey`, data);
  },

  getProfile: () => {
    return userApi.get(`${API_BASE_URL}/user/profile`);
  },

  getOtherUserProfile: (userId) => {
    return userApi.get(`${API_BASE_URL}/user/profile/${userId}`);
  },

  updateProfile: (formData) => {
    return userApi.put(`${API_BASE_URL}/user/profile`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },

  getInvitationHistory: (params) => {
    return userApi.get(`${API_BASE_URL}/user/invitation-history`, { params });
  },
};